package com.example.environment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.environment.pojo.*;
import com.example.environment.pojo.mapper.*;
import com.example.environment.service.VerificationService;
import com.example.environment.tools.common.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class VerificationServiceImpl extends ServiceImpl<VerificationMapper, Verification> implements VerificationService {

    @Autowired
    private VerificationMapper verificationMapper;
    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private FeedbackMapper feedbackMapper;
    @Autowired
    private SupervisorMapper supervisorMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private AqiStandardMapper aqiStandardMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 一级缓存，使用 ConcurrentHashMap
    private final Map<String, Map<String, Map<String, Object>>> cache = new ConcurrentHashMap<String, Map<String, Map<String, Object>>>();


    public ResultMsg getVerificationsByGsId(Integer gsId) {
        // 查询符合 gsId 的所有 verification 记录
        LambdaQueryWrapper<Verification> queryWrapper = Wrappers.lambdaQuery(Verification.class)
                .eq(Verification::getGsId, gsId).eq(Verification::getAssignWork,0);
        List<Verification> verificationList = verificationMapper.selectList(queryWrapper);

        // 查询 Staff 信息
        Staff staff = staffMapper.selectById(gsId);

        // 如果没有找到对应的 Staff，直接返回空列表
        if (staff == null) {
            return ResultMsg.failOp("该网格员没有被分派任务");
        }

        // 根据 feedbackIds 查询 Feedback 信息
        Set<String> feedbackIds = verificationList.stream()
                .map(Verification::getFeedbackId)
                .collect(Collectors.toSet());
        Map<String, Feedback> feedbackMap = feedbackMapper.selectBatchIds(feedbackIds).stream()
                .collect(Collectors.toMap(Feedback::getId, Function.identity()));
        Set<String> svIds = feedbackMap.values().stream().map(Feedback::getSvId).collect(Collectors.toSet());
        Set<Integer> AQIs = feedbackMap.values().stream().map(Feedback::getFeedbackAqi).collect(Collectors.toSet());
        // 根据 svIds 查询 Supervisor 信息
        Map<String, Supervisor> supervisorMap = supervisorMapper.selectBatchIds(svIds).stream()
                .collect(Collectors.toMap(Supervisor::getId, Function.identity()));
        Map<Integer, AqiStandard> AQIsMap = aqiStandardMapper.selectBatchIds(AQIs).stream()
                .collect(Collectors.toMap(AqiStandard::getAqiLevel, Function.identity()));
        // 查询 City 信息
        Set<Integer> cityIds = verificationList.stream()
                .map(Verification::getCityId)
                .collect(Collectors.toSet());
        Map<Integer, City> cityMap = cityMapper.selectBatchIds(cityIds).stream()
                .collect(Collectors.toMap(City::getId, Function.identity()));

        // 查询 Province 信息
        Set<Integer> provinceIds = verificationList.stream()
                .map(Verification::getProvinceId)
                .collect(Collectors.toSet());
        Map<Integer, Province> provinceMap = provinceMapper.selectBatchIds(provinceIds).stream()
                .collect(Collectors.toMap(Province::getId, Function.identity()));


        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Verification verification : verificationList) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("id", verification.getId());
            Feedback feedback = feedbackMap.get(verification.getFeedbackId());
            if (feedback != null) {
                dataMap.put("address", feedback.getAddress());
                dataMap.put("date", feedback.getDate());
                dataMap.put("content", feedback.getContent());
                dataMap.put("aqiLevel", feedback.getFeedbackAqi());
                AqiStandard aqiStandard=AQIsMap.get(feedback.getFeedbackAqi());
                if (aqiStandard != null) {
                    dataMap.put("aqiChinese", aqiStandard.getAqiChinese());//目前没找到用处，可删
                    dataMap.put("aqiExplain", aqiStandard.getAqiExplain());
                }
                Supervisor supervisor = supervisorMap.get(feedback.getSvId());
                if (supervisor != null) {
                    dataMap.put("svPhone", supervisor.getPhone());
                    dataMap.put("svName", supervisor.getName());
                }
            }

            City city = cityMap.get(verification.getCityId());
            if (city != null) {
                dataMap.put("city", city.getCity());
            }

            Province province = provinceMap.get(verification.getProvinceId());
            if (province != null) {
                dataMap.put("province", province.getProvince());
            }


            resultList.add(dataMap);
        }

        return ResultMsg.successOp(resultList);
    }

    @Override
    public ResultMsg addVerification(Verification verification) {
        verification.setId(UUID.randomUUID().toString());
        verification.setAssignWork(0);
        if(save(verification)){
            return ResultMsg.successOp("添加待处理验证成功");
        }
        return ResultMsg.failOp("添加待处理验证失败");
    }

    @Override
    public ResultMsg updateVerification(Verification verification, Integer id) {
        verification.setAssignWork(1);
        System.out.println(verification);
        if(updateById(verification)){
            return ResultMsg.successOp("修改待处理验证成功");
        }
        return ResultMsg.failOp("修改待处理验证失败");
    }


    public ResultMsg getVerificationList() {
               QueryWrapper<Verification> queryWrapper = new QueryWrapper<>();
               queryWrapper.eq("assign_work", 1);
        // 先从一级缓存中查找
                // 二级缓存（Redis）未命中，从数据库查询
                List<Verification> verificationList = verificationMapper.selectList(queryWrapper);
                if(verificationList==null){
                    return ResultMsg.failOp("确认表数据为空");
                }
                // 获取所有需要的主键集合
                Set<Integer> gsIds = verificationList.stream().map(Verification::getGsId).collect(Collectors.toSet());
                Set<String> feedbackIds = verificationList.stream().map(Verification::getFeedbackId).collect(Collectors.toSet());
                Set<Integer> cityIds = verificationList.stream().map(Verification::getCityId).collect(Collectors.toSet());
                Set<Integer> provinceIds = verificationList.stream().map(Verification::getProvinceId).collect(Collectors.toSet());
                Set<Integer> AQIs = verificationList.stream().map(Verification::getAqi).collect(Collectors.toSet());
                // 根据 gsIds 查询 Staff 信息
                Map<Integer, Staff> staffMap = staffMapper.selectBatchIds(gsIds).stream()
                        .collect(Collectors.toMap(Staff::getId, Function.identity()));

                // 根据 feedbackIds 查询 Feedback 信息
                Map<String, Feedback> feedbackMap = feedbackMapper.selectBatchIds(feedbackIds).stream()
                        .collect(Collectors.toMap(Feedback::getId, Function.identity()));

                // 获取所有 svIds
                Set<String> svIds = feedbackMap.values().stream().map(Feedback::getSvId).collect(Collectors.toSet());

                // 根据 svIds 查询 Supervisor 信息
                Map<String, Supervisor> supervisorMap = supervisorMapper.selectBatchIds(svIds).stream()
                        .collect(Collectors.toMap(Supervisor::getId, Function.identity()));

                // 根据 cityIds 查询 City 信息
                Map<Integer, City> cityMap = cityMapper.selectBatchIds(cityIds).stream()
                        .collect(Collectors.toMap(City::getId, Function.identity()));

                // 根据 provinceIds 查询 Province 信息
                Map<Integer, Province> provinceMap = provinceMapper.selectBatchIds(provinceIds).stream()
                        .collect(Collectors.toMap(Province::getId, Function.identity()));


                Map<Integer, AqiStandard> AQIsMap = aqiStandardMapper.selectBatchIds(AQIs).stream()
                        .collect(Collectors.toMap(AqiStandard::getAqiLevel, Function.identity()));

                // 整合数据到 VerificationVo
                List<Map<String, Object>>  verificationMap = new ArrayList<>();
                System.out.println(verificationList);
                for (Verification verification : verificationList) {
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("id", verification.getId());
                    dataMap.put("date", verification.getDate());
                    dataMap.put("time", verification.getTime());
                    dataMap.put("co", verification.getCo());
                    dataMap.put("aqi", verification.getAqi());
                    dataMap.put("pm", verification.getPm());
                    dataMap.put("sq2", verification.getSo2());

                    Staff staff = staffMap.get(verification.getGsId());
                    if (staff != null) {
                        dataMap.put("gsPhone", staff.getPhone());
                        dataMap.put("gsName", staff.getName());
                    }

                    Feedback feedback = feedbackMap.get(verification.getFeedbackId());
                    if (feedback != null) {
                        dataMap.put("address", feedback.getAddress());
                        dataMap.put("content", feedback.getContent());
                        Supervisor supervisor = supervisorMap.get(feedback.getSvId());
                        if (supervisor != null) {
                            dataMap.put("svPhone", supervisor.getPhone());
                            dataMap.put("svName", supervisor.getName());
                        }
                    }

                    City city = cityMap.get(verification.getCityId());
                    if (city != null) {
                        dataMap.put("city", city.getCity());
                    }

                    Province province = provinceMap.get(verification.getProvinceId());
                    if (province != null) {
                        dataMap.put("province", province.getProvince());
                    }
                    AqiStandard aqiStandard=AQIsMap.get(verification.getAqi());
                    if (aqiStandard != null) {
                        String str=aqiStandard.getAqiChinese()+"("+ aqiStandard.getAqiExplain()+")";
                        dataMap.put("aqiChinese", str);
                        dataMap.put("aqiColor", aqiStandard.getAqiColor());
                    }

                    verificationMap.add(dataMap);
                }

        return ResultMsg.successOp(verificationMap);
    }

    public ResultMsg getVerifyStaByProvince() {

        // 从数据库查询所有 verification 记录
        List<Verification> verificationList = verificationMapper.selectList(null);

        if(verificationList==null){
            return ResultMsg.failOp("待确认表为空");
        }
        Set<Integer> provinceIds = verificationList.stream()
                .map(Verification::getProvinceId)
                .collect(Collectors.toSet());
        Map<Integer, Province> provinceMap = provinceMapper.selectBatchIds(provinceIds).stream()
                .collect(Collectors.toMap(Province::getId, Function.identity()));
        // 分组统计
        Map<Integer, Map<String, Object>> statsMap = verificationList.stream()
                .collect(Collectors.groupingBy(
                        Verification::getProvinceId,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                    Map<String, Object> stats = new HashMap<>();
                                    stats.put("so2Count", list.stream().filter(v -> v.getSo2() != null && v.getSo2() > 150).count());
                                    stats.put("spmCount", list.stream().filter(v -> v.getPm() != null && v.getPm() > 75).count());
                                    stats.put("coCount", list.stream().filter(v -> v.getCo() != null && v.getCo() > 4).count());
                                    return stats;
                                }
                        )
                ));
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map.Entry<Integer, Map<String, Object>> entry : statsMap.entrySet()) {
            Integer provinceId = entry.getKey();
            Map<String, Object> stats = entry.getValue();

            Province province = provinceMap.get(provinceId);
            if (province != null) {
                stats.put("province", province.getProvince());
                stats.put("abbreviation", province.getAbbreviation());
            }
            resultList.add(stats);
        }
        return ResultMsg.successOp(resultList);
    }

    public ResultMsg getVerificationStats() {
        List<Map<String, Object>> statsList=new ArrayList<>();
        // 从数据库查询所有 verification 记录
        List<Verification> verificationList = verificationMapper.selectList(null);

        // 统计
        Map<String, Object> stats = new HashMap<>();

        // 对 aqi 进行分类统计
        long aqi0To50 = verificationList.stream().filter(v -> v.getAqi() != null && v.getAqi() == 1).count();
        long aqi50To100 = verificationList.stream().filter(v -> v.getAqi() != null && v.getAqi() == 2).count();
        long aqi100To150 = verificationList.stream().filter(v -> v.getAqi() != null && v.getAqi() == 3).count();
        long aqi150To200 = verificationList.stream().filter(v -> v.getAqi() != null && v.getAqi() == 4).count();
        long aqi200To300 = verificationList.stream().filter(v -> v.getAqi() != null && v.getAqi() == 5).count();
        long aqi300Above = verificationList.stream().filter(v -> v.getAqi() != null && v.getAqi() == 6).count();
        stats.put("description", "优");
        stats.put("aqiLevel", aqi0To50);
        statsList.add(stats);
        stats = new HashMap<>();
        stats.put("description", "轻度污染");
        stats.put("aqiLevel", aqi50To100);
        statsList.add(stats);
        stats = new HashMap<>();
        stats.put("description", "良");
        stats.put("aqiLevel", aqi100To150);
        statsList.add(stats);
         stats = new HashMap<>();
        stats.put("description", "中度污染");
        stats.put("aqiLevel", aqi150To200);
        statsList.add(stats);
         stats = new HashMap<>();
        stats.put("description", "重度污染");
        stats.put("aqiLevel", aqi200To300);
        statsList.add(stats);
         stats = new HashMap<>();
        stats.put("description", "严重污染");
        stats.put("aqiLevel", aqi300Above);
        statsList.add(stats);

        return ResultMsg.successOp(statsList);
    }

    public ResultMsg getAqiStatsByMonth() {
        // 从数据库查询所有 verification 记录
        List<Verification> verificationList = verificationMapper.selectList(null);

        List<Map<String,String>> statsList=new ArrayList<>();
        // 对记录按照年份和月份分组，并统计每组中 aqi 大于 100 的个数
        Map<String, Long> aqiStatsByMonth = verificationList.stream()
                .filter(v ->v.getDate()!=null) // Filter out entries where date is null
                .collect(Collectors.groupingBy(
                        v -> {
                            LocalDate date = LocalDate.parse(v.getDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                            return date.getYear() + "-" + String.format("%02d", date.getMonthValue());
                        },
                        Collectors.filtering(
                                v -> v.getAqi() != null && v.getAqi() >= 3, // Ensure AQI is not null and >= 3
                                Collectors.counting()
                        )
                ));

        for (Map.Entry<String,Long> entry : aqiStatsByMonth.entrySet()) {
            String month=entry.getKey();
            String count=entry.getValue().toString();
            Map<String, String> map = new HashMap<>();
            map.put("month",month);
            map.put("count",count);
            statsList.add(map);
        }

        return ResultMsg.successOp(statsList);
    }






}
